package com.hvisions.controller;

import com.hvisions.entity.Permission;
import com.hvisions.entity.User;
import com.hvisions.exception.GHException;
import com.hvisions.service.IPermissionService;
import com.hvisions.service.IUserService;
import com.hvisions.util.CoreConst;
import com.google.code.kaptcha.Constants;
import com.hvisions.util.ResultUtil;
import com.hvisions.util.ShiroUtils;
import com.hvisions.vo.base.ResponseVo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.Subject;
import org.crazycake.shiro.RedisCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.io.Serializable;
import java.util.Deque;
import java.util.List;
import java.util.Map;

/**
 * @Author: Lau
 * @Description: 登陆相关
 * @Date: Created in 9:05 2019/10/24
 * @Modified By:
 */
@Controller
public class SystemController {

    @Autowired
    IUserService userService;
    @Autowired
    IPermissionService permissionService;
    @Autowired
    private RedisCacheManager redisCacheManager;



    /**
     * 首页
     *
     * @return
     */
    @GetMapping(value = {"/", "index"})
    public String index() {
        return "index/index";
    }

    /*请求登陆页面*/
    @GetMapping("/login")
    public String login(Map map) {
        return "system/login";
    }


    /**
     * 提交登陆
     *
     * @param request
     * @param username
     * @param password
     * @param verification
     * @param rememberMe
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseVo login(HttpServletRequest request, String username, String password, String verification,
                            @RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
        //判断验证码
        try {
            String rightcode = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
            if (StringUtils.isNotBlank(verification) && verification.equals(rightcode)) {
                //验证通过
            } else {
                return ResultUtil.error("验证码错误");
            }
        }catch (GHException e){
            return ResultUtil.error("验证码失效");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            token.setRememberMe(1 == rememberMe);
            Subject currentUser = ShiroUtils.getSubject();
            currentUser.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResultUtil.error("用户已经被锁定不能登录，请联系管理员！");
        } catch (AuthenticationException e) {
            token.clear();
            return ResultUtil.error("用户名或者密码错误！");
        }
        //更新最后登录时间
        userService.updateLastLoginTime((User) SecurityUtils.getSubject().getPrincipal());
        return ResultUtil.success("登录成功！");
    }

    @RequestMapping("/logout")
    @ResponseBody
    public ResponseVo logout() {
        User user = ShiroUtils.getUserEntity();
        if (user != null) {
            String username = user.getUsername();
            Serializable sessionId = ShiroUtils.getSession().getId();
            Cache<String, Deque<Serializable>> cache = redisCacheManager.getCache(redisCacheManager.getKeyPrefix()+username);
            Deque<Serializable> deques = cache.get(username);
            for(Serializable deque : deques){
                if(sessionId.equals(deque)){
                    deques.remove(deque);
                    break;
                }
            }
            cache.put(username,deques);
        }
        ShiroUtils.logout();
        return ResultUtil.success("退出成功");
    }

    /**
     * 获取当前登陆用户的菜单(获取用户所有的权限)
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/menu")
    public List<Permission> getMenus() {
        List<Permission> list = permissionService.selectMenuByUserId(((User) SecurityUtils.getSubject().getPrincipal()).getUserId());
        return list;
    }

    /*图标*/
    @GetMapping(value = "/icons")
    public String getIcons() {
        return "ui/icons";
    }


}
